#include "ImaConf.h"
#include "ImaConstants.h"
#include "ImaLogger.h"
#include <string.h>
#include <jansson.h>

extern ImaLogger* gpLogger;

ImaConf::ImaConf(char *pConfFile) {
	char log_msg[1024];
	sprintf(log_msg, "ImaConf::ImaConf called with %s", (pConfFile != NULL) ? pConfFile : "NULL parameter");
	LOG(debug, __FILE__, __LINE__, log_msg); 

	if(pConfFile != NULL) {
		strcpy(mConfFile, pConfFile);
	} else {
		//TODO: throw exception
	}
}


int ImaConf::parseConfFile() {
	LOG(debug, __FILE__, __LINE__, "ImaConf::parseConfFile called");

	json_t* pRoot = NULL;
	json_error_t error;
	pRoot = json_load_file(mConfFile, 0, &error);
	if(!pRoot) {
		char log_msg[1024];
		sprintf(log_msg, "Failed to parse json conf file %s\n; error: %s\n", mConfFile, error.text);
		LOG(debug, __FILE__, __LINE__, log_msg);
		return -1;
	}	

	json_t* pAppServerHostObj = json_object_get(pRoot, IMA_JSON_KEY_APP_SERVER_HOST);
	if(pAppServerHostObj == NULL ) {
		LOG(error, __FILE__, __LINE__, "App Server hostname doesnt exist in the conf file");
		return -1;
	} else {
		if(json_is_string(pAppServerHostObj)) {
			strcpy(mAppServerHost, json_string_value(pAppServerHostObj));
		} else {
			LOG(error, __FILE__, __LINE__, "App server hostname should be a string value");
			return -1;
		}
	}

	json_t* pPortObj = json_object_get(pRoot, IMA_JSON_KEY_APP_SERVER_PORT);
	if(pPortObj == NULL) {
		char log_msg[1024];
		sprintf(log_msg, "Conf file %s doesn't contain the app server port", mConfFile);
		LOG(error, __FILE__, __LINE__, log_msg);
		json_decref(pRoot);
		return -1;
	} else {
		if(json_is_integer(pPortObj)) {
			mAppServerPort = json_integer_value(pPortObj);
		} else {
			LOG(error, __FILE__, __LINE__, "Port should be an integer object");
			json_decref(pRoot);
			return -1;
		}
	}

	json_decref(pRoot);
	return 0;
}

